from kivy.properties import ObjectProperty
from kivy.uix.screenmanager import ScreenManager, NoTransition


class GoblinScreenManager(ScreenManager):

    screen_stack = ObjectProperty()
    screen_provider = ObjectProperty()
    current_kwargs = ObjectProperty()

    def __init__(self, **kwargs):
        self.register_event_type('on_feed_refreshing')
        self.register_event_type('on_feed_refreshed')
        self.register_event_type('on_pull_to_refresh')
        self.register_event_type('on_no_service')
        self.transition = NoTransition()
        super(GoblinScreenManager, self).__init__(**kwargs)

    def on_feed_refreshing(self, *args):
        self.current_screen.dispatch('on_feed_refreshing', *args)
        return True

    def on_feed_refreshed(self, *args):
        self.current_screen.dispatch('on_feed_refreshed', *args)
        return True

    def on_pull_to_refresh(self, *args):
        self.current_screen.dispatch('on_pull_to_refresh', *args)
        return True

    def on_no_service(self, *args):
        self.current_screen.dispatch('on_no_service', *args)
        return True

    # Section: Screen Management
    # TODO: clean up this function

    def open_screen(self, **kwargs):
        new_screen = self.screen_provider.get_screen(**kwargs)
        if self.current_screen is not None:
            self.current_kwargs['dynamic_props'] = self.current_screen.get_dynamic_props()
            self.screen_stack.add_screen(self.current_kwargs)
            self.transition.direction = self.get_transition_dir(
                self.current_screen,
                new_screen)
        self.current_kwargs = kwargs
        self.switch_to(new_screen)

    def replace_screen(self, **kwargs):
        self.remove_widget(self.current_screen)
        self.open_screen(**kwargs)

    def has_previous_screen(self):
        return False if len(self.screen_stack.stack) == 0 else True

    def get_transition_dir(self, curr_screen, new_screen):
        if curr_screen.transition_priority > new_screen.transition_priority:
            return 'right'
        else:
            return 'left'

    def open_previous_screen(self):
        if self.has_previous_screen():
            previous_kwargs = self.screen_stack.pop_screen()
            screen = self.screen_provider.get_screen(**previous_kwargs)
            self.transition.direction = self.get_transition_dir(
                self.current_screen,
                screen)
            self.switch_to(screen)
            self.current_kwargs = previous_kwargs

    def refresh_current_screen(self):
        self.current_kwargs['dynamic_props'] = self.current_screen.get_dynamic_props()
        refreshed_screen = self.screen_provider.get_screen(**self.current_kwargs)
        self.switch_to(refreshed_screen)
